﻿namespace DCHealthCheck {

    #region Usings
    using DCHealthCheck.DomainModel;
    using Microsoft.GroupPolicy;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text; 
    #endregion

    public class GroupPolicySysvolInfoBuilder {

        #region Members
        private readonly GroupPolicySysvolInfo GroupPolicySysvolInfo;       
        #endregion

        #region Constructors
        private GroupPolicySysvolInfoBuilder() {
        }

        public GroupPolicySysvolInfoBuilder(GroupPolicySysvolInfo groupPolicySysvolInfo, string gpoDisplayName, string serverDirectoryPath)
            : this() {
            if (groupPolicySysvolInfo == null) {
                throw new ArgumentNullException("GroupPolicySysvolInfo groupPolicySysvolInfo cannot be null.");
            }
            if (gpoDisplayName == null) {
                throw new ArgumentNullException("gpoDisplayName cannot be null.");
            }
            if (serverDirectoryPath == null) {
                throw new ArgumentNullException("serverDirectoryPath cannot be null.");
            }

            this.GroupPolicySysvolInfo = groupPolicySysvolInfo;
            this.GroupPolicySysvolInfo.DirectoryPath = serverDirectoryPath;
            this.GroupPolicySysvolInfo.DisplayName = gpoDisplayName;
        } 
        #endregion

        #region Methods
        public GroupPolicySysvolInfo GetGroupPolicySysvolInfo() {
            string gptIniPath = Path.Combine(this.GroupPolicySysvolInfo.DirectoryPath, "gpt.ini");
            if (File.Exists(gptIniPath)) {
                this.GroupPolicySysvolInfo.CreatedUTC = File.GetCreationTimeUtc(gptIniPath);
                this.GroupPolicySysvolInfo.ModifiedUTC = File.GetLastWriteTimeUtc(gptIniPath);

                foreach (var line in File.ReadAllLines(gptIniPath)) {
                    if (line.StartsWith("Version=", StringComparison.OrdinalIgnoreCase)) {
                        this.GroupPolicySysvolInfo.Version = line.Replace("Version=", string.Empty).Trim();
                        break;
                    }
                }
            }

            return this.GroupPolicySysvolInfo;
        }

        public override string ToString() {
            if (this.GroupPolicySysvolInfo != null) {
                return this.GroupPolicySysvolInfo.ToString();
            }
            else {
                return string.Empty;
            }
        } 
        #endregion
    }
}
